<script setup lang="ts">
import {
  Cartesian2,
  Cartesian3,
  Color,
  ConstantProperty,
  UrlTemplateImageryProvider,
  Viewer,
} from 'cesium'
import { onMounted } from 'vue'

let viewer: Viewer

onMounted(() => {
  viewer = new Viewer('cesiumContainer', {
    // 搜索按钮
    geocoder: false,
    // 主页按钮
    homeButton: false,
    // 投影按钮
    sceneModePicker: false,
    // 图层选择按钮
    baseLayerPicker: false,
    // 帮助按钮
    navigationHelpButton: false,
    // 动画控件
    animation: false,
    // 时间线控件
    timeline: false,
    // 全屏按钮
    fullscreenButton: false,
    // 去掉版本
    creditContainer: document.createElement('div'),
    // 去掉星空背景
    skyBox: false,
    baseLayer: false,
    // 禁用信息框
    infoBox: false,
    // 禁用选中指示器
    selectionIndicator: false,
  })

  const subdomains = ['1', '2', '3', '4']

  // 高德影像底图
  const gaodeImageryProvider = new UrlTemplateImageryProvider({
    url: 'https://wprd0{s}.is.autonavi.com/appmaptile?x={x}&y={y}&z={z}&lang=zh_cn&style=6',
    subdomains: subdomains,
  })
  viewer.imageryLayers.addImageryProvider(gaodeImageryProvider)

  // 模拟数据
  const locations = [
    { id: 'point1', lon: 116.3365, lat: 39.5, name: 'A' },
    { id: 'point2', lon: 116.33, lat: 39.5, name: 'B' },
  ]

  // 渲染
  locations.forEach((loc) => {
    viewer.entities.add({
      id: loc.id,
      position: Cartesian3.fromDegrees(loc.lon, loc.lat),
      billboard: {
        image: '/location_fill_yellow.png',
        width: 30,
        height: 30,
      },
      label: {
        text: loc.name,
        font: '14px Helvetica',
        // 文字颜色
        fillColor: Color.WHITE,
        // 不显示背景色
        showBackground: false,
        // 垂直偏移
        pixelOffset: new Cartesian2(0, -30),
      },
    })
  })

  viewer.camera.flyTo({
    destination: Cartesian3.fromDegrees(116.33, 39.5, 2700),
  })
})
const changeAlarm = (id: string) => {
  // 查找A点
  const entity = viewer.entities.getById(id)
  if (entity) {
    if (entity.billboard) {
      entity.billboard.image = new ConstantProperty('/location_fill_red.png')
    }
    if (entity.label) {
      entity.label.fillColor = new ConstantProperty(Color.RED)
    }
  }
}

const reset = (id: string) => {
  const entity = viewer.entities.getById(id)
  if (entity) {
    if (entity.billboard) {
      entity.billboard.image = new ConstantProperty('/location_fill_yellow.png')
    }
    if (entity.label) {
      entity.label.fillColor = new ConstantProperty(Color.WHITE)
    }
  }
}
</script>

<template>
  <div id="cesiumContainer"></div>
  <div class="operateBox">
    <button @click="changeAlarm('point1')">A点报警</button>
    <button @click="reset('point1')">A点复位</button>
  </div>
</template>

<style scoped>
.operateBox {
  position: absolute;
  top: 16px;
  right: 32px;
}

.operateBox button {
  padding: 6px 16px;
  margin-left: 16px;
}
</style>
